package cn.itcast.server;

import cn.itcast.message.PingMessage;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import cn.itcast.server.service.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import static io.netty.handler.timeout.IdleState.READER_IDLE;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 消息处理器 handler
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_SINGLETON_HANDLER = new ChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        QuitRemindHandler QUIT_HANDLER = new QuitRemindHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder()); //处理黏包半包
//                    ch.pipeline().addLast(LOGGING_HANDLER); //日志打印
                    ch.pipeline().addLast(MESSAGE_CODEC); //消息协议，配合数据处理器共同解析数据

                    ch.pipeline().addLast(new IdleStateHandler(5,
                                                    0,0)); //读监测，限定时间后触发
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        // 处理特殊事件
                        // 负责处理读监测
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if(((IdleStateEvent)evt).state() == READER_IDLE){
                                ctx.channel().close(); // 限定时间内未响应，通道关闭
                            }
                        }
                    });
                    ch.pipeline().addLast(LOGIN_HANDLER); //处理登录信息
                    ch.pipeline().addLast(CHAT_SINGLETON_HANDLER); // 处理私聊信息
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER); // 处理建群请求
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER); // 处理加群请求
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER); // 处理群聊信息
                    ch.pipeline().addLast(GROUP_MEMBERS_HANDLER); // 处理获取群成员请求
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER); // 处理退群请求
                    ch.pipeline().addLast(QUIT_HANDLER); // 注销处理
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();

            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
